﻿using Dao;
using HospitalErpWinUI;
using HospitalErpWinUI.GlobalVar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Columns;
using DevExpress.Utils;
using System.Configuration;
namespace HospitalErpWinUI.hbos.acct.vouch.query.newinsert
{
    public partial class main : Form
    { 
        private DaoHelper _helper = new DaoHelper();
        private DataTable acct_dt = null;　//财务凭证明细
        private DataTable budg_dt = null;　//预算凭证明细
        private DataTable items_dt = new DataTable();　//辅助核算明细
        private DataTable bing_items_dt = null;//辅助核算明细绑定用
        private DataTable look_acct_dt = null; //财务科目下拉科目
        private DataTable type_dy = null;//凭证类型对应关系
        private int new_vouch_id = 0;
        private string new_vouch_detail_id = "-1";
        private string new_acct_subj_code = "";
        #region 初始化
        public main()
        {
            InitializeComponent();
        }
        private void main_Load(object sender, EventArgs e)
        {
            ControlInit();
            GridInit();
            gridViewacct.AddNewRow();
        }

        /// <summary>
        /// 初始各个下拉空间
        /// </summary>
        private void ControlInit()
        {
            //获取会计凭证与预算凭证的对应关系
            Dictionary<string, string> type_paramter = new Dictionary<string, string>();
            type_dy = _helper.ReadSqlForDataTable(new ServiceParamter("cs_vouch_type_gx_get", type_paramter));

            vouch_date.DateTime = DateTime.Parse(G_User.user.LoginDate);
            //获取最大凭证号

            Dictionary<string, string> paramter = new Dictionary<string, string>();
            paramter.Add("comp_code",G_User.user.Comp_code);
            paramter.Add("copy_code",G_User.user.Copy_code);
            paramter.Add("check_method", "1");

            DataTable dt_vouch_type = _helper.ReadSqlForDataTable(new ServiceParamter("newacct_vouch_type_list", paramter));

            //会计凭证分类
            acct_type.Properties.DataSource = dt_vouch_type;
            acct_type.Properties.DisplayMember = "vouch_type_name";
            acct_type.Properties.ValueMember = "vouch_type_code";
            acct_type.ItemIndex = 0;
            //预算凭证分类
            Dictionary<string, string> budg_paramter = new Dictionary<string, string>();
            budg_paramter.Add("comp_code", G_User.user.Comp_code);
            budg_paramter.Add("copy_code", G_User.user.Copy_code);
            budg_paramter.Add("check_method", "2");
            DataTable dt_budg_type = _helper.ReadSqlForDataTable(new ServiceParamter("newacct_vouch_type_list", budg_paramter));

            budg_type.Properties.DataSource = dt_budg_type;
            budg_type.Properties.DisplayMember = "vouch_type_name";
            budg_type.Properties.ValueMember = "vouch_type_code";

            DataRow[] tydrs = type_dy.Select("acct_type='" + acct_type.EditValue + "'");
            if (tydrs.Length > 0)
            {
                budg_type.EditValue = tydrs[0]["budg_type"].ToString();
            }

            //会计科目
            Dictionary<string, string> pacct_acct_subj = new Dictionary<string, string>();
            pacct_acct_subj.Add("check_method", "1");
            DataTable dt_acct_acct_subj = _helper.ReadSqlForDataTable(new ServiceParamter("cs_acct_subj_select", pacct_acct_subj));
            GridLookUpAcct_acct_subj.DataSource = dt_acct_acct_subj;
            look_acct_dt = dt_acct_acct_subj;

            //预算科目
            Dictionary<string, string> pbudg_acct_subj = new Dictionary<string, string>();
            pbudg_acct_subj.Add("check_method", "2");
            DataTable dt_budg_acct_subj = _helper.ReadSqlForDataTable(new ServiceParamter("cs_acct_subj_select", pbudg_acct_subj));
            GridLookUpbudg_acct_subj.DataSource = dt_budg_acct_subj;

            get_max_vouch_no();
        }

        //凭证类型改变事件
        private void acct_type_EditValueChanged(object sender, EventArgs e)
        {
            if (budg_type.EditValue!=null)
            {
                DataRow[] tydrs = type_dy.Select("acct_type='" + acct_type.EditValue + "'");
                if (tydrs.Length > 0)
                {
                    budg_type.EditValue = tydrs[0]["budg_type"].ToString();
                }
            }
            if (acct_vouch_no.EditValue != null)
            {
                get_max_vouch_no();
            }
        }
        private void vouch_date_EditValueChanged(object sender, EventArgs e)
        {
            if (acct_vouch_no.EditValue != null)
            {
                get_max_vouch_no();
            }
        }
        //获取最大凭证号
        private void get_max_vouch_no()
        {
            Dictionary<string, string> p_vouch_no = new Dictionary<string, string>();
            p_vouch_no.Add("vouch_date", vouch_date.DateTime.ToString());
            p_vouch_no.Add("vouch_type", acct_type.EditValue.ToString());
            DataTable dt_vouch_no = _helper.ReadSqlForDataTable(new ServiceParamter("cs_vouch_no_get", p_vouch_no));

            if (dt_vouch_no.Rows.Count > 0)
            {
                acct_vouch_no.EditValue = dt_vouch_no.Rows[0][0].ToString();
            }
        }
        

        /// <summary>
        /// 初始网格
        /// </summary>
        private void GridInit()
        {
            DataTable tbacct = new DataTable("tbacct");
            tbacct.Columns.Add("vouch_detail_id", Type.GetType("System.String"));
            tbacct.Columns.Add("vouch_id", Type.GetType("System.Int32"));
            tbacct.Columns.Add("vouch_page", Type.GetType("System.Int32"));
            tbacct.Columns.Add("vouch_row", Type.GetType("System.Int32"));
            tbacct.Columns.Add("summary", Type.GetType("System.String"));
            tbacct.Columns.Add("acct_subj_code", Type.GetType("System.String"));
            tbacct.Columns.Add("amt_debit", Type.GetType("System.Double"));
            tbacct.Columns.Add("amt_credit", Type.GetType("System.Double"));

            DataRow dr;
            int rowCount = 200 - tbacct.Rows.Count;
            for (int i = 0; i < rowCount; i++)
            {
                dr = tbacct.NewRow();
                tbacct.Rows.Add(dr);
            }
            gridacct.DataSource = tbacct;
            acct_dt = tbacct;

            DataTable tbbudg = new DataTable("tbacct");
            tbbudg.Columns.Add("vouch_detail_id", Type.GetType("System.String"));
            tbbudg.Columns.Add("vouch_id", Type.GetType("System.Int32"));
            tbbudg.Columns.Add("vouch_page", Type.GetType("System.Int32"));
            tbbudg.Columns.Add("vouch_row", Type.GetType("System.Int32"));
            tbbudg.Columns.Add("summary", Type.GetType("System.String"));
            tbbudg.Columns.Add("acct_subj_code", Type.GetType("System.String"));
            tbbudg.Columns.Add("amt_debit", Type.GetType("System.Double"));
            tbbudg.Columns.Add("amt_credit", Type.GetType("System.Double"));

            DataRow dr2;
            int rowCount2 = 200 - tbbudg.Rows.Count;
            for (int i = 0; i < rowCount; i++)
            {
                dr2 = tbbudg.NewRow();
                tbbudg.Rows.Add(dr2);
            }
            gridbudg.DataSource = tbbudg;
            budg_dt = tbbudg;

        }
        #endregion

        #region 事件
        private void but_vouch_save_Click(object sender, EventArgs e)
        {
            string url = ConfigurationManager.AppSettings["ServicesAdress"] + "/Vouch/Add";
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("", create_jison().Trim());
            HttpHelper.CreateHttpPostResponse(url, dic, G_User.user.Ticket, "vouchInsert");
        }

        /// <summary>
        /// 根据表生成jison
        /// </summary
        private string create_jison()
        {
            //select vouch_id,budg_vouch_id,comp_code,copy_code,acct_year,operator,acct_month,vouch_no,vouch_date,vouch_bill_num,vouch_type_code,vouch_source_code
            //,is_check,is_acc,is_cx,is_cancel,is_tell,is_chknot
            // from acct_vouch where is_check=0 and acct_year='2019'
            gridViewbudg.UpdateCurrentRow();
            gridViewacct.UpdateCurrentRow();

            string vouchjison = "[";
            string budg_vouchj = "{\"is_budg\":\"1\",\"vouch_id\":\"\",\"budg_vouch_id\":\"\",\"comp_code\":\"" + G_User.user.Comp_code + "\" ,\"copy_code\":\"" + G_User.user.Copy_code
                + "\" ,\"acct_year\":\"" + G_User.user.Acct_year + "\",\"operator\":\"" + G_User.user.UserName + "\",\"acct_month\":\"" + Mid(vouch_date.DateTime.ToString("u"),5,2)
                + "\",\"vouch_no\":\"" + budg_vouch_no.EditValue.ToString() + "\",\"vouch_date\":\"" + vouch_date.DateTime.ToString("d") + "\",\"vouch_bill_num\":\""
                + bill_num.EditValue.ToString() + "\",\"vouch_type_code\":\"" + budg_type.EditValue.ToString() + "\",\"vouch_source_code\":\"01\""
                + ",\"is_check\":\"0\",\"is_acc\":\"0\",\"is_cx\":\"0\",\"is_cancel\":\"0\",\"is_tell\":\"0\",\"is_chknot\":\"0\"";

            string budg_details = "";
            if (budg_dt.Rows.Count > 0)
            {
                budg_details = ",\"vouch_detials\":[";
                foreach (DataRow dr in budg_dt.Select("acct_subj_code is not null or acct_subj_code<>''"))
                {
                    if (Right(budg_details, 1) == "}")
                    {
                        budg_details = budg_details + ",{\"comp_code\":\"" + G_User.user.Comp_code + "\" ,\"copy_code\":\"" + G_User.user.Copy_code
                            + "\" ,\"acct_year\":\"" + G_User.user.Acct_year + "\",";
                    }
                    else
                    {
                        budg_details = budg_details + "{\"comp_code\":\"" + G_User.user.Comp_code + "\" ,\"copy_code\":\"" + G_User.user.Copy_code
                            + "\" ,\"acct_year\":\"" + G_User.user.Acct_year + "\",";
                    }
                    foreach (DataColumn dc in budg_dt.Columns)
                    {
                        if (Right(budg_details, 1) == ",")
                        {
                            if ((dc.ColumnName == "amt_debit" && (dr[dc.ColumnName].ToString() == String.Empty || dr[dc.ColumnName].ToString() == "")) || (dc.ColumnName == "amt_credit" && (dr[dc.ColumnName].ToString() == String.Empty || dr[dc.ColumnName].ToString() == "")))
                            { budg_details = budg_details + "\"" + dc.ColumnName + "\":\"0\""; }
                            else
                            { budg_details = budg_details + "\"" + dc.ColumnName + "\":\"" + dr[dc.ColumnName] + "\""; }
                        }
                        else
                        {
                            if ((dc.ColumnName == "amt_debit" && (dr[dc.ColumnName].ToString() == String.Empty || dr[dc.ColumnName].ToString() == "")) || (dc.ColumnName == "amt_credit" && (dr[dc.ColumnName].ToString() == String.Empty || dr[dc.ColumnName].ToString() == "")))
                            { budg_details = budg_details + ",\"" + dc.ColumnName + "\":\"0\""; }
                            else
                            { budg_details = budg_details + ",\"" + dc.ColumnName + "\":\"" + dr[dc.ColumnName] + "\""; }
                        }
                    }
                    DataRow[] drs = items_dt.Select("vouch_detail_id = '" + dr["vouch_detail_id"].ToString() + "' and (acct_subj_code is not null or acct_subj_code<>'')");
                    if (drs.Length > 0)
                    {
                        budg_details = budg_details + ",\"check_items\":[";
                        foreach (DataRow drr in drs)
                        {
                            if (Right(budg_details, 1) == "}")
                            {
                                budg_details = budg_details + ",{\"comp_code\":\"" + G_User.user.Comp_code + "\" ,\"copy_code\":\"" + G_User.user.Copy_code
                                    + "\" ,\"acct_year\":\"" + G_User.user.Acct_year + "\",";
                            }
                            else
                            {
                                budg_details = budg_details + "{\"comp_code\":\"" + G_User.user.Comp_code + "\" ,\"copy_code\":\"" + G_User.user.Copy_code
                                    + "\" ,\"acct_year\":\"" + G_User.user.Acct_year + "\",";
                            }
                            foreach (DataColumn dcc in items_dt.Columns)
                            {
                                if (Right(budg_details, 1) == ",")
                                {
                                    if (dcc.ColumnName == "amt_money" )
                                    {
                                        if (decimal.Parse(dr["amt_debit"].ToString() == String.Empty ? "0" : dr["amt_debit"].ToString()) >= decimal.Parse(dr["amt_credit"].ToString() == String.Empty ? "0" : dr["amt_credit"].ToString()))
                                        { budg_details = budg_details + "\"amt_debit\":\"" + drr[dcc.ColumnName] + "\""; }
                                        else
                                        { budg_details = budg_details + "\"amt_credit\":\"" + drr[dcc.ColumnName] + "\""; }
                                    }
                                    else
                                    { budg_details = budg_details + "\"" + dcc.ColumnName + "\":\"" + drr[dcc.ColumnName] + "\""; }
                                }
                                else
                                {
                                    if (dcc.ColumnName == "amt_money")
                                    {
                                        if (decimal.Parse(dr["amt_debit"].ToString() == String.Empty ? "0" : dr["amt_debit"].ToString()) >= decimal.Parse(dr["amt_credit"].ToString() == String.Empty ? "0" : dr["amt_credit"].ToString()))
                                        { budg_details = budg_details + ",\"amt_debit\":\"" + drr[dcc.ColumnName] + "\""; }
                                        else
                                        { budg_details = budg_details + ",\"amt_credit\":\"" + drr[dcc.ColumnName] + "\""; }
                                    }
                                    else
                                    { budg_details = budg_details + ",\"" + dcc.ColumnName + "\":\"" + drr[dcc.ColumnName] + "\""; }
                                }
                            }
                            budg_details = budg_details + "}";
                        }
                        budg_details = budg_details + "]";
                    }
                    budg_details = budg_details + "}";
                }
                
            }
            if (budg_details.Length > 18)
            {
                budg_vouchj = budg_vouchj + budg_details + "]}";
            }
            else
            {
                budg_vouchj = budg_vouchj + "}";
            }
            string acct_vouchj = ",{\"is_budg\":\"0\",\"vouch_id\":\"\",\"budg_vouch_id\":\"\",\"comp_code\":\"" + G_User.user.Comp_code + "\" ,\"copy_code\":\"" + G_User.user.Copy_code
                + "\" ,\"acct_year\":\"" + G_User.user.Acct_year + "\",\"operator\":\"" + G_User.user.UserName + "\",\"acct_month\":\"" + Mid(vouch_date.DateTime.ToString("u"), 5, 2)
                + "\",\"vouch_no\":\"" + acct_vouch_no.EditValue.ToString() + "\",\"vouch_date\":\"" + vouch_date.DateTime.ToString("d") + "\",\"vouch_bill_num\":\""
                + bill_num.EditValue.ToString() + "\",\"vouch_type_code\":\"" + acct_type.EditValue.ToString() + "\",\"vouch_source_code\":\"01\""
                + ",\"is_check\":\"0\",\"is_acc\":\"0\",\"is_cx\":\"0\",\"is_cancel\":\"0\",\"is_tell\":\"0\",\"is_chknot\":\"0\"";

            string acct_details = "";
            if (acct_dt.Rows.Count > 0)
            {
                acct_details = ",\"vouch_detials\":[";
                foreach (DataRow dr in acct_dt.Select("acct_subj_code is not null or acct_subj_code<>''"))
                {
                    if (Right(acct_details, 1) == "}")
                    {
                        acct_details = acct_details + ",{\"comp_code\":\"" + G_User.user.Comp_code + "\" ,\"copy_code\":\"" + G_User.user.Copy_code
                            + "\" ,\"acct_year\":\"" + G_User.user.Acct_year + "\",";
                    }
                    else
                    {
                        acct_details = acct_details + "{\"comp_code\":\"" + G_User.user.Comp_code + "\" ,\"copy_code\":\"" + G_User.user.Copy_code
                            + "\" ,\"acct_year\":\"" + G_User.user.Acct_year + "\",";
                    }
                    foreach (DataColumn dc in acct_dt.Columns)
                    {
                        if (Right(acct_details, 1) == ",") 
                        {
                            if ((dc.ColumnName == "amt_debit" && (dr[dc.ColumnName].ToString() == String.Empty || dr[dc.ColumnName].ToString() == "")) || (dc.ColumnName == "amt_credit" && (dr[dc.ColumnName].ToString() == String.Empty || dr[dc.ColumnName].ToString() == "")))
                            { acct_details = acct_details + "\"" + dc.ColumnName + "\":\"0\""; }
                            else
                            { acct_details = acct_details + "\"" + dc.ColumnName + "\":\"" + dr[dc.ColumnName] + "\""; }
                        }
                        else
                        {
                            if ((dc.ColumnName == "amt_debit" && (dr[dc.ColumnName].ToString() == String.Empty || dr[dc.ColumnName].ToString() == "")) || (dc.ColumnName == "amt_credit" && (dr[dc.ColumnName].ToString() == String.Empty || dr[dc.ColumnName].ToString() == "")))
                            { acct_details = acct_details + ",\"" + dc.ColumnName + "\":\"0\""; }
                            else
                            { acct_details = acct_details + ",\"" + dc.ColumnName + "\":\"" + dr[dc.ColumnName] + "\""; }
                        }
                    }
                    DataRow[] drs = items_dt.Select("vouch_detail_id = '" + dr["vouch_detail_id"].ToString() + "' and (acct_subj_code is not null or acct_subj_code<>'')");
                    if (drs.Length > 0)
                    {
                        acct_details = acct_details + ",\"check_items\":[";
                        foreach (DataRow drr in drs)
                        {
                            if (Right(acct_details, 1) == "}")
                            {
                                acct_details = acct_details + ",{\"comp_code\":\"" + G_User.user.Comp_code + "\" ,\"copy_code\":\"" + G_User.user.Copy_code
                                    + "\" ,\"acct_year\":\"" + G_User.user.Acct_year + "\",";
                            }
                            else
                            {
                                acct_details = acct_details + "{\"comp_code\":\"" + G_User.user.Comp_code + "\" ,\"copy_code\":\"" + G_User.user.Copy_code
                                    + "\" ,\"acct_year\":\"" + G_User.user.Acct_year + "\",";
                            }
                            foreach (DataColumn dcc in items_dt.Columns)
                            {
                                if (Right(acct_details, 1) == ",")
                                {
                                    if (dcc.ColumnName == "amt_money")
                                    {
                                        if (decimal.Parse(dr["amt_debit"].ToString() == String.Empty ? "0" : dr["amt_debit"].ToString()) >= decimal.Parse(dr["amt_credit"].ToString() == String.Empty ? "0" : dr["amt_credit"].ToString()))
                                        { budg_details = budg_details + "\"amt_debit\":\"" + drr[dcc.ColumnName] + "\""; }
                                        else
                                        { budg_details = budg_details + "\"amt_credit\":\"" + drr[dcc.ColumnName] + "\""; }
                                    }
                                    else
                                    { acct_details = acct_details + "\"" + dcc.ColumnName + "\":\"" + drr[dcc.ColumnName] + "\""; }
                                }
                                else
                                {
                                    if (dcc.ColumnName == "amt_money")
                                    {
                                        if (decimal.Parse(dr["amt_debit"].ToString() == String.Empty ? "0" : dr["amt_debit"].ToString()) >= decimal.Parse(dr["amt_credit"].ToString() == String.Empty ? "0" : dr["amt_credit"].ToString()))
                                        { budg_details = budg_details + ",\"amt_debit\":\"" + drr[dcc.ColumnName] + "\""; }
                                        else
                                        { budg_details = budg_details + "\"amt_credit\":\"" + drr[dcc.ColumnName] + "\""; }
                                    }
                                    else
                                    { acct_details = acct_details + ",\"" + dcc.ColumnName + "\":\"" + drr[dcc.ColumnName] + "\""; }
                                }
                            }
                            acct_details = acct_details + "}";
                        }
                        acct_details = acct_details + "]";
                    }
                    acct_details = acct_details + "}";
                }

            }
            if (acct_details.Length > 18)
            {
                acct_vouchj = acct_vouchj + acct_details + "]}";
            }
            else
            {
                acct_vouchj = acct_vouchj + "}";
            }

            vouchjison = vouchjison + budg_vouchj + acct_vouchj + "]";
            return vouchjison;
        }
        public static string Mid(string param, int startIndex, int length)
        {
            string result = param.Substring(startIndex, length);
            return result;
        }
        public static string Right(string param, int length)
        {
            string result = param.Substring(param.Length - length, length);
            return result;
        }
        
        /// <summary>
        /// 关闭窗口
        /// </summary>
        private void but_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 预算网格选中行
        /// </summary>
        private void gridViewbudg_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            string row_acct_subj_code = "";
            if (e.FocusedRowHandle >= 0)
            {
                if (budg_dt != null)
                {
                    row_acct_subj_code = budg_dt.Rows[e.FocusedRowHandle]["acct_subj_code"].ToString();
                    if (budg_dt.Rows[e.FocusedRowHandle]["vouch_id"].ToString() == null || budg_dt.Rows[e.FocusedRowHandle]["vouch_id"].ToString() == "")
                    {
                        budg_dt.Rows[e.FocusedRowHandle]["vouch_id"] = new_vouch_id;
                    }
                    if (budg_dt.Rows[e.FocusedRowHandle]["vouch_detail_id"].ToString() == null || budg_dt.Rows[e.FocusedRowHandle]["vouch_detail_id"].ToString() == "")
                    {
                        budg_dt.Rows[e.FocusedRowHandle]["vouch_detail_id"] = "budg_" + e.FocusedRowHandle.ToString();
                    }

                    new_vouch_detail_id = budg_dt.Rows[e.FocusedRowHandle]["vouch_detail_id"].ToString();
                    new_acct_subj_code = budg_dt.Rows[e.FocusedRowHandle]["acct_subj_code"].ToString();

                    if (row_acct_subj_code != null && row_acct_subj_code != "")
                    {
                        init_checkitems(row_acct_subj_code);
                    }
                    else
                    {
                        init_checkitems("");
                    }
                }
            }
        }

        /// <summary>
        /// 财务网格选中行
        /// </summary>
        private void gridViewacct_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            string row_acct_subj_code = "";
            if (e.FocusedRowHandle >= 0)
            {
                if (acct_dt != null)
                {
                    row_acct_subj_code = acct_dt.Rows[e.FocusedRowHandle]["acct_subj_code"].ToString();
                    if (acct_dt.Rows[e.FocusedRowHandle]["vouch_id"].ToString() == null || acct_dt.Rows[e.FocusedRowHandle]["vouch_id"].ToString() == "")
                    {
                        acct_dt.Rows[e.FocusedRowHandle]["vouch_id"] = new_vouch_id;
                    }
                    if (acct_dt.Rows[e.FocusedRowHandle]["vouch_detail_id"].ToString() == null || acct_dt.Rows[e.FocusedRowHandle]["vouch_detail_id"].ToString() == "")
                    {
                        acct_dt.Rows[e.FocusedRowHandle]["vouch_detail_id"] = "acct_"+e.FocusedRowHandle.ToString();
                    }

                    new_vouch_detail_id = acct_dt.Rows[e.FocusedRowHandle]["vouch_detail_id"].ToString();
                    new_acct_subj_code = acct_dt.Rows[e.FocusedRowHandle]["acct_subj_code"].ToString();

                    if (row_acct_subj_code != null && row_acct_subj_code != "")
                    {
                        init_checkitems(row_acct_subj_code);
                    }
                    else
                    {
                        init_checkitems("");
                    }
                }
            }
        }
        /// <summary>
        /// 财务会计得到焦点
        /// </summary>
        private void gridViewacct_GotFocus(object sender, EventArgs e)
        {
            string row_acct_subj_code = "";
            if (!gridViewbudg.IsFocusedView)
            {
                if (gridViewacct.FocusedRowHandle >= 0)
                {
                    if (acct_dt != null)
                    {
                        row_acct_subj_code = acct_dt.Rows[gridViewacct.FocusedRowHandle]["acct_subj_code"].ToString();
                        if (acct_dt.Rows[gridViewacct.FocusedRowHandle]["vouch_id"].ToString() == null || acct_dt.Rows[gridViewacct.FocusedRowHandle]["vouch_id"].ToString() == "")
                        {
                            acct_dt.Rows[gridViewacct.FocusedRowHandle]["vouch_id"] = new_vouch_id;
                        }
                        if (acct_dt.Rows[gridViewacct.FocusedRowHandle]["vouch_detail_id"].ToString() == null || acct_dt.Rows[gridViewacct.FocusedRowHandle]["vouch_detail_id"].ToString() == "")
                        {
                            acct_dt.Rows[gridViewacct.FocusedRowHandle]["vouch_detail_id"] = "acct_" + gridViewacct.FocusedRowHandle.ToString();
                        }

                        new_vouch_detail_id = acct_dt.Rows[gridViewacct.FocusedRowHandle]["vouch_detail_id"].ToString();
                        new_acct_subj_code = acct_dt.Rows[gridViewacct.FocusedRowHandle]["acct_subj_code"].ToString();

                        if (row_acct_subj_code != null && row_acct_subj_code != "")
                        {
                            init_checkitems(row_acct_subj_code);
                        }
                        else
                        {
                            init_checkitems("");
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 预算得到焦点
        /// </summary>
        private void gridViewbudg_GotFocus(object sender, EventArgs e)
        {
            string row_acct_subj_code = "";
            if (!gridViewacct.IsFocusedView)
            {
                if (budg_dt != null)
                {
                    row_acct_subj_code = budg_dt.Rows[gridViewbudg.FocusedRowHandle]["acct_subj_code"].ToString();
                    if (budg_dt.Rows[gridViewbudg.FocusedRowHandle]["vouch_id"].ToString() == null || budg_dt.Rows[gridViewbudg.FocusedRowHandle]["vouch_id"].ToString() == "")
                    {
                        budg_dt.Rows[gridViewbudg.FocusedRowHandle]["vouch_id"] = new_vouch_id;
                    }
                    if (budg_dt.Rows[gridViewbudg.FocusedRowHandle]["vouch_detail_id"].ToString() == null || budg_dt.Rows[gridViewbudg.FocusedRowHandle]["vouch_detail_id"].ToString() == "")
                    {
                        budg_dt.Rows[gridViewbudg.FocusedRowHandle]["vouch_detail_id"] = "budg_" + gridViewbudg.FocusedRowHandle.ToString();
                    }

                    new_vouch_detail_id = budg_dt.Rows[gridViewbudg.FocusedRowHandle]["vouch_detail_id"].ToString();
                    new_acct_subj_code = budg_dt.Rows[gridViewbudg.FocusedRowHandle]["acct_subj_code"].ToString();

                    if (row_acct_subj_code != null && row_acct_subj_code != "")
                    {
                        init_checkitems(row_acct_subj_code);
                    }
                    else
                    {
                        init_checkitems("");
                    }
                }
            }
        }

        /// <summary>
        /// 加载辅助核算表格
        /// </summary>
        private void init_checkitems(string acct_subj_code)
        {
            if (acct_subj_code == "")
            {
                init_checkitems_delete();
            }
            else
            {
                DataTable dt_item_init = new DataTable();

                Dictionary<string, string> pacct_acct_subj = new Dictionary<string, string>();
                pacct_acct_subj.Add("acct_subj_code", acct_subj_code);
                DataTable dt_check = _helper.ReadSqlForDataTable(new ServiceParamter("cs_getcheckitems_model", pacct_acct_subj));
                string row_type = "";
                string row_code = "";
                int row_width = 0;

                if (dt_check.Rows.Count > 2)
                {
                    init_checkitems_delete();
                    gridViewitems.Columns.Add(new GridColumn() { Name = "acct_check_id", FieldName = "acct_check_id", Caption = "acct_check_id", Visible = false });
                    gridViewitems.Columns.Add(new GridColumn() { Name = "vouch_detail_id", FieldName = "vouch_detail_id", Caption = "vouch_detail_id", Visible = false });
                    gridViewitems.Columns.Add(new GridColumn() { Name = "acct_subj_code", FieldName = "acct_subj_code", Caption = "acct_subj_code", Visible = false });
                    
                    dt_item_init.Columns.Add("acct_check_id", Type.GetType("System.String"));
                    dt_item_init.Columns.Add("vouch_detail_id", Type.GetType("System.String"));
                    dt_item_init.Columns.Add("acct_subj_code", Type.GetType("System.String"));

                    if (!items_dt.Columns.Contains("acct_check_id"))
                    {
                        items_dt.Columns.Add("acct_check_id", Type.GetType("System.String"));
                    }
                    if (!items_dt.Columns.Contains("vouch_detail_id"))
                    {
                        items_dt.Columns.Add("vouch_detail_id", Type.GetType("System.String"));
                    }
                    if (!items_dt.Columns.Contains("acct_subj_code"))
                    {
                        items_dt.Columns.Add("acct_subj_code", Type.GetType("System.String"));
                    }

                    for (int i = 0; i < dt_check.Rows.Count; i++)
                    {
                        row_type = dt_check.Rows[i]["row_type"].ToString();
                        row_code = dt_check.Rows[i]["row_code"].ToString();

                        if (dt_check.Rows[i]["width"].ToString() != null || dt_check.Rows[i]["width"].ToString() != "")
                        {
                            row_width = int.Parse(dt_check.Rows[i]["width"].ToString());
                        }

                        if (row_type=="text")
                        {
                            if (!items_dt.Columns.Contains(row_code))
                            {
                                items_dt.Columns.Add(row_code, Type.GetType("System.String"));
                            }
                            dt_item_init.Columns.Add(row_code, Type.GetType("System.String"));
                            gridViewitems.Columns.Add(new GridColumn() { Name = dt_check.Rows[i]["row_code"].ToString(), FieldName = dt_check.Rows[i]["row_code"].ToString(), Caption = dt_check.Rows[i]["row_name"].ToString(), Visible = true, Width = row_width });
                        }
                        else if (row_type == "lookup")
                        {
                            if (!items_dt.Columns.Contains(row_code))
                            {
                                items_dt.Columns.Add(row_code, Type.GetType("System.String"));
                            }
                            dt_item_init.Columns.Add(row_code, Type.GetType("System.String"));
                            gridViewitems.Columns.Add(new GridColumn() { Name = dt_check.Rows[i]["row_code"].ToString(), FieldName = dt_check.Rows[i]["row_code"].ToString(), Caption = dt_check.Rows[i]["row_name"].ToString(), Visible = true, Width = row_width });

                            gridViewitems.Columns[dt_check.Rows[i]["row_code"].ToString()].ColumnEdit = CreateGridLookUp(dt_check.Rows[i]["row_code"].ToString(), dt_check.Rows[i]["row_sqlid"].ToString(), row_width);
                        }
                        else if (row_type == "num")
                        {
                            if (!items_dt.Columns.Contains(row_code))
                            {
                                items_dt.Columns.Add(row_code, Type.GetType("System.Double"));
                            }
                            dt_item_init.Columns.Add(row_code, Type.GetType("System.Double"));
                            GridColumn gc1 = new GridColumn() { Name = dt_check.Rows[i]["row_code"].ToString(), FieldName = dt_check.Rows[i]["row_code"].ToString(), Caption = dt_check.Rows[i]["row_name"].ToString(), Visible = true, Width = row_width };
                            gc1.DisplayFormat.FormatType = FormatType.Numeric;
                            gc1.DisplayFormat.FormatString = "{0:N2}";
                            gridViewitems.Columns.Add(gc1);
                        }
                        else if (row_type == "num4")
                        {
                            if (!items_dt.Columns.Contains(row_code))
                            {
                                items_dt.Columns.Add(row_code, Type.GetType("System.Double"));
                            }
                            dt_item_init.Columns.Add(row_code, Type.GetType("System.Double"));
                            GridColumn gc1 = new GridColumn() { Name = dt_check.Rows[i]["row_code"].ToString(), FieldName = dt_check.Rows[i]["row_code"].ToString(), Caption = dt_check.Rows[i]["row_name"].ToString(), Visible = true, Width = row_width };
                            gc1.DisplayFormat.FormatType = FormatType.Numeric;
                            gc1.DisplayFormat.FormatString = "{0:N4}";
                            gridViewitems.Columns.Add(gc1);
                        }
                        else if (row_type == "date")
                        {
                            if (!items_dt.Columns.Contains(row_code))
                            {
                                items_dt.Columns.Add(row_code, Type.GetType("System.DateTime"));
                            }
                            dt_item_init.Columns.Add(row_code, Type.GetType("System.DateTime"));
                            GridColumn gc1 = new GridColumn() { Name = dt_check.Rows[i]["row_code"].ToString(), FieldName = dt_check.Rows[i]["row_code"].ToString(), Caption = dt_check.Rows[i]["row_name"].ToString(), Visible = true, Width = row_width };
                            gc1.DisplayFormat.FormatType = FormatType.Numeric;
                            gc1.DisplayFormat.FormatString = "{YYYY/MM/DD}";
                            gridViewitems.Columns.Add(gc1);
                        }
                    }

                    DataRow[] temdrs = items_dt.Select("vouch_detail_id = '" + new_vouch_detail_id + "'");
                    if (temdrs.Length > 0)
                    {
                        foreach (DataRow fdr in temdrs)
                        {
                            DataRow drtemp = dt_item_init.NewRow();
                            foreach (DataColumn fdc in dt_item_init.Columns)
                            {
                                drtemp[fdc.ColumnName] = fdr[fdc.ColumnName];
                            }
                            dt_item_init.Rows.Add(drtemp);
                        }
                    }

                    griditems.DataSource = dt_item_init;
                    bing_items_dt = dt_item_init;
                }
                else
                {
                    init_checkitems_delete();
                }
            }
        }

        /// <summary>
        /// 生成可选下拉
        /// </summary>
        private DevExpress.XtraEditors.Repository.RepositoryItemGridLookUpEdit CreateGridLookUp(string gname, string sqlid,int row_width)
        {
            Dictionary<string, string> para_itemslook = new Dictionary<string, string>();
            para_itemslook.Add("checkname", gname);
            DataTable dt_ilook = _helper.ReadSqlForDataTable(new ServiceParamter(sqlid, para_itemslook));

            DevExpress.XtraEditors.Repository.RepositoryItemGridLookUpEdit templookup = new DevExpress.XtraEditors.Repository.RepositoryItemGridLookUpEdit();
            DevExpress.XtraGrid.Views.Grid.GridView tempview = new DevExpress.XtraGrid.Views.Grid.GridView();
            tempview.Name = "itemgridview" + gname;
            tempview.OptionsView.ShowAutoFilterRow = true;
            tempview.Columns.Add(new GridColumn() { Name = dt_ilook.Columns[0].ColumnName, FieldName = dt_ilook.Columns[0].ColumnName, Caption = "编码", Visible = false, Width = row_width });
            tempview.Columns.Add(new GridColumn() { Name = dt_ilook.Columns[1].ColumnName, FieldName = dt_ilook.Columns[1].ColumnName, Caption = "名称", Visible = true, Width = row_width });
            
            templookup.Name = "itemgridlook" + gname;
            templookup.View = tempview;
            
            templookup.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
            templookup.NullText = "";
            templookup.ShowFooter = false;
            templookup.AutoComplete = false;
            templookup.ImmediatePopup = true;
            templookup.PopupFilterMode = DevExpress.XtraEditors.PopupFilterMode.Contains;
            templookup.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;

            templookup.DataSource = dt_ilook;
            templookup.DisplayMember = dt_ilook.Columns[1].ColumnName;
            templookup.ValueMember = dt_ilook.Columns[0].ColumnName;

            return templookup;
        }

        /// <summary>
        /// 加载辅助核算表格
        /// </summary>
        private void init_checkitems_delete()
        {
            int row = gridViewitems.RowCount;
            int col = gridViewitems.Columns.Count;
            for (int i = 0; i < row; i++)
            {
                gridViewitems.DeleteRow(0);
            }
            for (int i = 0; i < col; i++)
            {
                gridViewitems.Columns.Remove(gridViewitems.Columns[0]);
            }
        }

        /// <summary>
        /// 辅助核算表值改变事件
        /// </summary>
        private void gridViewitems_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.ToLower() != "vouch_detail_id" && e.Column.FieldName.ToLower() != "acct_check_id")
            {
                gridViewitems.UpdateCurrentRow();
                if (gridViewitems.GetRowCellValue(gridViewitems.FocusedRowHandle, "vouch_detail_id") == null || gridViewitems.GetRowCellValue(gridViewitems.FocusedRowHandle, "vouch_detail_id").ToString() == "")
                {
                    gridViewitems.SetRowCellValue(gridViewitems.FocusedRowHandle, "vouch_detail_id", new_vouch_detail_id);
                }
                if (gridViewitems.GetRowCellValue(gridViewitems.FocusedRowHandle, "acct_check_id") == null || gridViewitems.GetRowCellValue(gridViewitems.FocusedRowHandle, "acct_check_id").ToString() == "")
                {
                    gridViewitems.SetRowCellValue(gridViewitems.FocusedRowHandle, "acct_check_id", System.Guid.NewGuid().ToString());
                }
                if (gridViewitems.GetRowCellValue(gridViewitems.FocusedRowHandle, "acct_subj_code") == null || gridViewitems.GetRowCellValue(gridViewitems.FocusedRowHandle, "acct_subj_code").ToString() == "")
                {
                    gridViewitems.SetRowCellValue(gridViewitems.FocusedRowHandle, "acct_subj_code", new_acct_subj_code);
                }
                DataView nowdv = (DataView)gridViewitems.DataSource;
                DataTable nowdt = nowdv.Table;
                DataRow tempdr = nowdt.Rows[gridViewitems.FocusedRowHandle];
                DataRow[] temdrs = items_dt.Select("acct_check_id = '" + tempdr["acct_check_id"].ToString() + "'");
                DataRow adddr = items_dt.NewRow();
                
                foreach (DataColumn cl in nowdt.Columns)
                {
                    if (temdrs.Length>0)
                    {
                        if (cl.ColumnName != "vouch_detail_id" && cl.ColumnName != "acct_check_id")
                        {
                            temdrs[0][cl.ColumnName] = tempdr[cl.ColumnName];
                        }
                    }
                    else
                    {
                        adddr[cl.ColumnName] = tempdr[cl.ColumnName];
                    }
                }

                if (temdrs.Length <= 0)
                {
                    items_dt.Rows.Add(adddr);
                }
            }
        }
        #endregion

        //凭证号变动，同时修改预算凭证号
        private void acct_vouch_no_EditValueChanged(object sender, EventArgs e)
        {
            budg_vouch_no.EditValue = acct_vouch_no.EditValue;
        }


         //private void lookacct_subj_code_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        //{
        //    DevExpress.XtraEditors.LookUpEdit mylookup = sender as DevExpress.XtraEditors.LookUpEdit;

        //    string content = mylookup.EditValue.ToString();
        //    if (!string.IsNullOrEmpty(content) && look_acct_dt.Rows.Count > 0)
        //    {
        //        mylookup.ClosePopup();
        //        DataTable newdt = new DataTable();
        //        newdt = look_acct_dt.Copy();
        //        newdt.Rows.Clear();
        //        DataRow[] drs = look_acct_dt.Select("acct_subj_name like '%" + content + "%'");
        //        foreach (DataRow dr in drs)
        //        {
        //            newdt.ImportRow(dr);
        //        }
        //        mylookup.Properties.DataSource = newdt;
        //        mylookup.Properties.DropDownRows = newdt.Rows.Count;
        //        mylookup.ShowPopup();
        //        return;
        //    }
        //}

    }
}
